<template>
  <div class="paper">
    <!-- 答题卡 -->
    <div class="paper-left">
      <el-card shadow="never" class="paper-left-top" style="background-color: #fafafa;">
        <!-- <el-avatar size="large"/> -->
        <!-- <div class="userContent">
          <img
            :src="userStore.avaterUrl"
            class="avatar"
            v-if="userStore.avaterUrl"
          />
          <UserOutlined v-else class="avatar-uploader-icon" />
          <span class="paper-left-top-username">
            <span> {{ user.name }}</span> <span> {{ user.orgName }}</span>
          </span>
        </div> -->
        <div class="paper-left-top-statis">
          <div>
            <Iconfont
              icon="icon-jiangbei"
              :size="20"
              color="#F6961E;"
              :width="30"
              :height="30"
              :radius="5"
              background-color="#FDF3E7"
            />
            <span class="paper-left-top-statis-value"
              >{{ examQuestions.length }}道</span
            >

            <span class="paper-left-top-statis-txt">试题数量</span>
          </div>
        </div>

        <fontSet  />
        <el-button type="primary" plain @click="$router.go(-1)">返回</el-button>
      </el-card>
      <el-card shadow="never" class="paper-left-bottom" style="background-color: #fafafa;">
        <el-divider> 答题卡 </el-divider>
        <el-scrollbar height="calc(100vh - 316px)">
          <template v-for="(examQuestion, index) in examQuestions">
            <el-button
            :data-no="examQuestion.no"
            :type="errMark(examQuestion).type"
            :plain="errMark(examQuestion).plain"
            @click="toNav(examQuestion.no)"
            >{{ examQuestion.no }}</el-button
          >
          </template>
        </el-scrollbar>
      </el-card>
    </div>
    <!-- 试卷 -->
    <el-scrollbar max-height="calc(100vh - 50px)" class="paper-right">
      <el-card shadow="never" style="background-color: #fafafa;">
        <!-- 右上角显示打分 -->
        <div class="paper-right-score" v-if="scoreShow">
          <span class="paper-right-score-value">{{ myExam.totalScore }}</span>
          <span class="iconfont icon-fenshudixian"></span>
        </div>
        <!-- 试卷名称 -->
        <div class="paper-right-title">
          <el-input
            :value="exer.name"
            :maxlength="16"
            placeholder=""
            :readonly="true"
          />
        </div>
        <!-- 试题列表 -->
        <div
          v-for="(examQuestion, index) in examQuestions"
          :key="index"
          v-if="examQuestions.length"
        >
          <QuestionVue
            :no="index + 1"
            :type="examQuestion.type"
            :markType="1"
            :title="examQuestion.title"
            :score="examQuestion.score"
            :answers="examQuestion.answers"
            :userScore="examQuestion.userScore"
            :userAnswers="examQuestion.userAnswers"
            :options="examQuestion.options"
            :editable="!exer.answerShow && examQuestion.userScore === null"
            @change="(answers: string[]) => answerUpdate(examQuestion, answers,index)"
            :user-answer-show="!exer.answerShow"
            :errShow="!exer.answerShow && examQuestion.userScore !== null"
          >
            <template #bottom-right>
              <el-tooltip
                placement="top"
                effect="light"
                :content="answerFormat(examQuestion)"
                popper-class="popper-class"
              >
                <el-button type="success" size="small">标准答案</el-button>
              </el-tooltip>
            </template>
            <template #bottom>
              <div class="questionBottom">
                <span class="heartContent" @click="favClick(examQuestion)">
                  <DeleteFilled class="heart" />删除错题
                </span>
                <FeedbackComponent
                  feedbackTitle="题目纠错"
                  v-if="examQuestion.questionId"
                  :questionId="examQuestion.questionId"
                />
              </div>
            </template>
          </QuestionVue>
        </div>
        <a-skeleton active v-else />
      </el-card>
    </el-scrollbar>
  </div>
</template>
<script lang="ts" setup>
import http from "@/request";
import { computed, onMounted, onUnmounted, reactive, ref, nextTick } from "vue";
import QuestionVue from "@/components/question/Question.vue";
import FeedbackComponent from "@/components/feedback.vue";
import type { ExamQuestion } from "@/stores/exer";
import _ from "lodash";
import CountDown from "@/components/CountDown.vue";
import dayjs from "dayjs";
import { ElMessageBox, type Action } from "element-plus";
import { DeleteFilled,UserOutlined} from "@ant-design/icons-vue";
import { useRouter, useRoute } from "vue-router";
import { useDictStore } from "@/stores/dict";
import fontSet from "@/components/fontSet.vue";
import { noticStore } from "@/stores/notic";
import { useUserStore } from "@/stores/user";

// 定义变量
const userStore = useUserStore();
const noticFn = noticStore();
const route = useRoute();
const router = useRouter();
const dictStore = useDictStore(); // 字典缓存
const examQuestions = ref([] as ExamQuestion[]); // 试卷信息
const questionErrNum = ref(0); // 错题数
const exer = reactive({
  // 考试信息
  id: 0, // 考试ID
  name: "", // 试卷名称
  color: "", // 倒计时颜色
  markState: 0, // 阅卷状态
  scoreState: 0, // 分数状态
  rankState: 0, // 排名状态
  answerShow: true, // 是否显示答案
});
const changeanswer = (value) => {
  // 改变答案显示
  exer.answerShow = value;
};
const myExam = reactive({
  // 我的考试信息
  id: 0, // 考试ID
  name: "", // 试卷名称
});
const user = reactive({
  // 用户信息
  name: "", // 姓名
  orgName: "", // 机构名称
});

// 组件挂载完成后，执行如下方法
onMounted(async () => {
  // 获取机构信息

  let {
    data: { data: data2 },
  } = await http.post("user/get", {});
  user.name = data2.name;
  user.orgName = data2.orgName;
  // 获取我的考试信息
  exer.id = parseInt(route.params.exerId as string);
  let {
    data: { data, code },
  } = await http.post("myCollect/paper", { questionTypeId: exer.id, type: 1 });

  examQuestions.value = data;
  examQuestions.value.forEach((item, index) => {
    item.no = index + 1;
    item.userAnswers = [];
    item.userScore = null;
    item.errShow = false;
  });
});

// 在页面初始化时执行该函数，将存储的答案赋值到 examQuestions 题目列表中

// 组件卸载完成后，执行如下方法
onUnmounted(() => {});

// 计算属性
// 是否答题。未考试且未阅卷显示（未考试且考试结束时间到，后台会处理成未考试且已阅卷）；考试中显示
const scoreShow = false;
const updateQuestion = (question) => {
  examQuestions.value.forEach((item, index) => {
    if (item.questionId == question.questionId) {
      item = question;
    }
  });
};
const favClick = async (question) => {


  let data2 = await http.post("myCollect/del", {
    id: question.id,
  });
  if (data2.data.code == 200) {
    // 删除成功，examQuestions删除该题
    examQuestions.value.forEach((item, index) => {
      if (item.questionId == question.questionId) {
        examQuestions.value.splice(index, 1);
      }
    });
    // 如果xamQuestions.value长度为0，跳转回我的收藏
    if (examQuestions.value.length == 0) {
      router.push({ path: "/myCollect" });
    }
  }
};
// 答题
const answerUpdate = _.debounce(async function (examQuestion, answers, index) {
  // _.debounce返回的包装后的函数，所以能正常传参
  let found = false;
  //查看noticFn.myExerInfozz中是否有这场考试
  noticFn.myExerInfo.forEach((item) => {
    if (item.id === exer.id) {
      let questionFound = false;
      item.questions.forEach((q) => {
        if (q.questionId === examQuestion.questionId) {
          q.answers = answers;
          questionFound = true;
        }
      });

      if (!questionFound) {
        item.questions.push({
          questionId: examQuestion.questionId,
          answers: answers,
        });
      }
      item.currentIndex = index;
      found = true;
    }
  });

  if (!found) {
    noticFn.myExerInfo.push({
      id: exer.id,
      currentIndex: index,
      questions: [
        {
          questionId: examQuestion.questionId,
          answers: answers,
        },
      ],
    });
  }

  let {
    data: { data, code },
  } = await http.post("exmMyExer/save", {
    type: 1,
    content: JSON.stringify(noticFn.myExerInfo),
  });
  //找到答题卡中这道题
  examQuestions.value[examQuestion.no - 1].userAnswers = answers;
}, 500); // 延时一秒体验不好，填完直接返回没提交

// 交卷
async function finish() {
  //判断对错
  examQuestions.value.forEach((item) => {
    const result = determineRight(item);
    if (result.userScore !== 1) {
      // 如果用户得分不是满分，即做错了
      questionErrNum.value++;
    }
  });
}

//判断该题是否正确
function determineRight(question) {
  // 数据有效性校验

  // 如果是答题模式，选择错误时，标记错误

  if (question.type === 1 || question.type === 4) {
    // 如果是单选或判断
    if (question.userScore == null) {
      // 如果没打分
      question.userScore = 0; // 将其初始化为 0
      if (question.userAnswers && question.userAnswers[0]) {
        // 如果有答案
        if (question.userAnswers[0] === question.answers[0]) {
          // 打分
          question.userScore = 1;
        }
      }
    }
  }
  if (question.type === 2) {
    // 如果是多选
    if (question.userScore == null) {
      // 如果没打分
      question.userScore = 0; // 将其初始化为 0
      if (question.userAnswers && question.userAnswers[0]) {
        // 如果有答案
        let include = question.userAnswers.every((userAnswer) =>
          question.answers.includes(userAnswer)
        );
        if (
          include &&
          question.answers.length === question.userAnswers.length
        ) {
          // 打分
          question.userScore = 1;
        } else if (include) {
          question.userScore = 0.5;
        }
      }
    }
  }
  return question;
}

// 考试结束

// 答题导航
function toNav(no) {
  if (no) {
    (document.querySelector(`#question-${no}`) as HTMLElement).scrollIntoView(
      true
    );
  }
}

// 时间差值

// 时间差值的分钟数
function errMark(examQuestion: ExamQuestion) {
  let question = examQuestion;
  if (!question.userAnswers?.length) {
    // 如果没有作答，默认颜色
    return { type: "", plain: false };
  } else {
    return { type: "primary", plain: true };
  }
}
function answerFormat(question: Question) {
  if (
    question.type === 1 || // 单选
    question.type === 4 || // 判断
    (question.type === 5 && question.markType === 2)
  ) {
    // 主观问答
    return (
      question.answers &&
      question.answers[0] &&
      question.answers[0].replaceAll("\n", "<br/>")
    );
  }
  if (question.type === 2) {
    // 多选
    return question.answers?.toString().replaceAll(",", "");
  }

  if (
    question.type === 3 || // 填空
    (question.type === 5 && question.markType === 1)
  ) {
    // 客观问答
    let answerFormat = "";
    question.answers?.forEach((answer: string, index: number) => {
      answerFormat += `${question.type === 3 ? "填空" : "关键词"}${
        index + 1
      }：${answer.replaceAll("\n", "、")}<br/>`;
    });

    return answerFormat;
  }
}
</script>


<style lang="scss" scoped>
.paper {
  flex: 1;
  display: flex;
  margin-bottom: 10px;
  .paper-left {
    width: 320px;
    display: flex;
    flex-direction: column;
    .paper-left-top {
      margin-bottom: 10px;
      background-color: #fafafa;
      :deep(.el-card__body) {
        display: flex;
        flex-direction: column;
        align-items: center;
        padding: 10px 10px;
        .el-avatar {
          border: 2px solid var(--el-color-primary);
          margin-bottom: 10px;
        }
        .paper-left-top-username {
          font-size: 16px;
          font-weight: bold;
          color: #333;
        }
        .paper-left-top-statis {
          display: flex;
          width: 100%;
          div {
            flex: 1;
            margin: auto;
            .paper-left-top-statis-value {
              font-size: 14px;
              font-weight: bold;
              padding-top: 8px;
              display: block;
              text-align: center;
            }
            .jg {
              color: #25b864;
            }
            .nojg {
              color: #ff0000;
            }
            .paper-left-top-statis-txt {
              font-size: 14px;
              font-weight: bold;
              color: #333;
              display: block;
              text-align: center;
            }
          }
        }
        .paper-left-top-time {
          border: 1px dashed var(--el-color-primary);
          padding: 5px;
          margin-top: 20px;
          width: 100%;
          span {
            font-weight: bold;
            font-size: 14px;
            color: var(--el-color-primary);
            margin: auto;
            display: block;
            text-align: center;
          }
        }
        .el-button {
          width: 100%;
          margin-top: 10px;
          margin-left: 0px;
        }
      }
    }

    .paper-left-bottom {
      .el-divider--horizontal {
        margin: 15px 0px 20px 0px;
      }
      .el-button {
        height: 50px;
        width: 50px;
        padding: 0;
        margin: 2px;
        font-size: 18px;
      }
      .paper-left-bottom-chapter {
        font-size: 13px;
        font-weight: bold;
        margin: 5px 0px;
        cursor: pointer;
      }
    }
  }

  :deep(.paper-right) {
    flex: 1;
    .el-card {
      min-height: calc(100vh - 50px);
      margin-left: 10px;
      position: relative;
      &:hover {
        .paper-right-toolbar {
          display: block;
        }
      }
      .paper-right-toolbar {
        position: absolute;
        right: 10px;
        top: 5px;
        display: none;
        z-index: 2;
      }

      .paper-right-score {
        position: absolute;
        right: 30px;
        top: 30px;
        z-index: 2;

        display: flex;
        flex-direction: column;
        color: red;
        font-size: 26px;

        .iconfont {
          font-size: 58px;
          line-height: 30px;
        }
        .paper-right-score-value {
          text-align: center;
        }
      }

      .paper-right-title {
        margin-top: 10px;

        .el-input__wrapper {
          box-shadow: initial;
          background-color: #fafafa;
                    .el-input__inner {
            background-color: #fafafa;
            text-align: center;
            font-size: 24px;
            font-weight: bold;
            color: #333;
          }
        }
      }

      .paper-right-chapter {
        padding: 0px 20px;
        position: relative;
        &:hover {
          .el-button {
            display: inline-block;
          }
        }
        .el-input__wrapper {
          box-shadow: initial;
          background-color: #fafafa;
                    .el-input__inner {
            background-color: #fafafa;
            font-size: 16px;
            font-weight: bold;
          }
        }
        .el-textarea__inner {
          box-shadow: initial;
        }
        .el-button {
          position: absolute;
          bottom: 5px;
          right: 5px;
          display: none;
        }
        .el-form-item {
          // 校验通过时，恢复和章节描述的距离
          margin-bottom: 0;
          &.is-error {
            margin-bottom: 18px;
          }
        }
        .el-form-item__error {
          margin-left: 12px;
        }
      }
    }
  }
}
</style>
<style lang="scss" scoped>
.popper-class {
  max-width: 800px;
}
.el-radio__input.is-disabled + span.el-radio__label {
  color: #333;
  font-size: 15px;
}
.questionBottom {
  margin-top: 10px;
  display: flex;
  align-items: center;
}
.heartContent {
  font-size: 16px;
  cursor: pointer;
  display: flex;
  align-items: center;
  .heart {
    margin-right: 4px;
    font-size: 18px;
    color: #f50;
  }
}
.buttonContent {
  display: flex;
  width: 297px;
}
.userContent {
  display: flex;
  align-items: center;
  margin-bottom: 13px;
}
.paper-left-top-username {
  display: flex;
  flex-direction: column;
}
.avatar {
  width: 35px;
  height: 35px;
  border-radius: 50%; /* 设置圆形头像框 */
  object-fit: cover; /* 图片填充头像框 */
  margin-right: 6px;
}
.avatar-uploader-icon {
  font-size: 28px;
  margin-right: 6px;
}
</style>